package com.itsu.integration.demo;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.util.TypeUtils;
import com.itsu.integration.demo.service.CIO020Req;
import com.itsu.integration.demo.service.CIO020Rsp;
import com.itsu.integration.demo.service.ObjectFactory;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;
import org.springframework.ws.client.core.WebServiceTemplate;

import javax.xml.bind.JAXBElement;
import javax.xml.namespace.QName;


//@Component
public class CallSoapEndpoint {

    public Message<?> transform(Message<?> inMessage) throws Exception {
        System.out.println("xXXXXXXXXXXXXXXXXXXXXXXXXXXTransformEndpoint.transform XXXXXXXXXXXXX");

        String payloadJsonStr = inMessage.getPayload().toString();
        CIO020Req request = new ObjectFactory().createCIO020Req();
		request = JSONObject.parseObject(payloadJsonStr, CIO020Req.class);

		Message<?> message = MessageBuilder.withPayload(request).build();
        return message;
    }

	public Message<?> callSOAP(Message<?> inMessage) {

		System.out.println("xXXXXXXXXXXXXXXXXXXXXXXXXXX CallSoapEndpoint.callSOAP XXXXXXXXXXXXX");

		WebServiceTemplate soapClient = new WebServiceTemplate();
		soapClient.setMarshaller(marshaller());
		soapClient.setUnmarshaller(marshaller());

		Message<?> message = MessageBuilder.withPayload("").build();
		try {

			inMessage = transform(inMessage);
			//json convert to soap
			//System.out.println("xXXXX  build soap request XXXXXXXXXXXXX" +payloadStr);
			QName qname=new QName("soa","CIO020Req");
			
			JAXBElement<CIO020Req> jaxbReq = new JAXBElement<CIO020Req>(qname,CIO020Req.class,(CIO020Req) inMessage.getPayload());
	
			JAXBElement<CIO020Rsp> response = (JAXBElement<CIO020Rsp>) soapClient.marshalSendAndReceive("http://127.0.0.1:8081/ws",jaxbReq);
			
			System.out.println("==============BANK CODE IS "+response.getValue().getEmsHeader().getBankCode());
			TypeUtils.compatibleWithFieldName = true;
			String responseJsonStr=	JSONObject.toJSONString(response.getValue());
			//System.out.println(responseJsonStr);

			message = MessageBuilder.withPayload(responseJsonStr).build();
		} catch (Exception e) {
			System.out.println("XXXX "+e.getMessage());
		} finally{
			return message;
		}

	}

	public static Jaxb2Marshaller marshaller() {
		Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
		// this package must match the package in the <generatePackage> specified in
		// pom.xml
		marshaller.setContextPath("com.itsu.integration.demo.service");
		return marshaller;
	}
	
}
